#ifdef ESP32
#include <WiFi.h>
#else
#include <ESP8266WiFi.h>
#endif
// #define ESP32
#include <WiFiManager.h> // https://github.com/tzapu/WiFiManager

#include <PubSubClient.h>
#define STATUS 13
#define PW_PIN 5
#define RST_PIN 4
unsigned long lastTime = 0, lastOperate = 0;
char mqtt_server[] = "lubo1982.mycloudnas.com";
const char *mqttUser = "lu";
const char *mqttPassWd = "5891381";
const int port = 1883;
WiFiClient espClient;
PubSubClient client(espClient);
int i = 0;
char outTopic[30], inTopic[30];
void powerKey()
{
    digitalWrite(PW_PIN, 1);
    delay(800);
    digitalWrite(PW_PIN, 0);
}
void rstKey()
{
    digitalWrite(RST_PIN, 1);
    delay(800);
    digitalWrite(RST_PIN, 0);
}
void callback(char *topic, byte *payload, unsigned int length)
{
    Serial.print("R[");
    Serial.print(topic);
    Serial.print("]:");
    String msg = "";
    for (int i = 0; i < length; i++)
    {
        msg += (char)payload[i];
        //    Serial.print((char)payload[i]);
    }
    Serial.println(msg);
    if (strcmp(msg.c_str(), "POW") == 0)
    {
        if (digitalRead(PW_PIN) == 1)
        {
            if (millis() - lastOperate >= 30000)
            {
                lastOperate = millis();
                Serial.println("PW switch operatored!");
                powerKey();
            }
            else
                Serial.println("PW switch blocked!");
        }
        else
        {
            Serial.println("PW switch operatored!");
            powerKey();
        }
    }
    if (strcmp(msg.c_str(), "RST") == 0)
    {
        Serial.println("RST switch operatored!");
        rstKey();
    }
}
void reconnect()
{
    while (!client.connected())
    {
        Serial.print("Attempting MQTT connection...");
        if (client.connect("arduinoClient", mqttUser, mqttPassWd))
        {
            Serial.println("connected");
            subScribe();
        }
        else
        {
            Serial.print("failed, rc=");
            Serial.print(client.state());
            Serial.println(" try again in 5 seconds");
            delay(5000);
        }
    }
}

void subScribe()
{
    client.subscribe(inTopic);
    Serial.printf("subScribe the topic[%s]\n", inTopic);
}
bool wifiConnect()
{
    WiFiManager wm;
    bool res;
    uint8_t macAddr[6];
    WiFi.macAddress(macAddr);
    char SSID[20];
    int i = 0;
    sprintf(SSID, "Computer-%X%X", macAddr[4], macAddr[5]);
    if (WiFi.status() != WL_CONNECTED)
    {
        wm.setTimeout(180);
        wm.setConnectTimeout(30);
        res = wm.autoConnect(SSID);
        WiFi.hostname("ComputerControl"); // 连接后再设置host
        if (!res)
        {
            //    Serial.println("Failed to connect");
            return 0;
        }
        else
        {
            //    Serial.println("connected...yeey :)");
            return 1;
        }
    }
    else
    {

        return 1;
    }
}
void setup()
{
    Serial.begin(115200);
    pinMode(STATUS, INPUT);
    pinMode(PW_PIN, OUTPUT);
    pinMode(RST_PIN, OUTPUT);
    pinMode(2, OUTPUT);
    digitalWrite(PW_PIN, 0);
    digitalWrite(RST_PIN, 0);
    if (wifiConnect() == 0)
        ESP.restart();
    uint8_t macAddr[6];
    WiFi.macAddress(macAddr);
    client.setServer(mqtt_server, port);
    client.setCallback(callback);
    sprintf(outTopic, "Computer/Status%X%X", macAddr[4], macAddr[5]);
    sprintf(inTopic, "Computer/Control%X%X", macAddr[4], macAddr[5]);
    reconnect();
}
void loop()
{
    char msg[20];
    if (wifiConnect() == 0)
        ESP.restart();
    if (!client.connected())
    {
        reconnect();
    }
    client.loop();
    if (millis() - lastTime >= 2000)
    {
        lastTime = millis();
        sprintf(msg, "%s", digitalRead(STATUS) ? "ON" : "OFF");
        digitalWrite(2, digitalRead(STATUS) ? 0 : 1);
        Serial.printf("T[%s]:%s\n", outTopic, msg);
        client.publish(outTopic, msg);
    }
}